import os
import sqlite3
import shutil
from datetime import datetime
import argparse

def get_new_filename_if_exists(destination_path):
    """如果目标文件存在，则返回一个新文件名"""
    base, ext = os.path.splitext(destination_path)
    while os.path.exists(destination_path):
        new_base = f"{base}_{datetime.now().strftime('%H%M%S')}"
        destination_path = new_base + ext
    return destination_path

def move_files_and_update_db(db_conn, base_dir):
    """遍历file_merge表并移动文件"""
    cursor = db_conn.cursor()
    cursor.execute('SELECT id, file_path, aim_folder FROM file_merge WHERE deal_flag=0')
    rows = cursor.fetchall()
    
    for row in rows:
        id, source_path, aim_folder = row
        destination_dir = os.path.join(base_dir, aim_folder)
        destination_path = os.path.join(destination_dir, os.path.basename(source_path))
        
        # 检查源文件是否存在
        if not os.path.exists(source_path):
            print(f'Source file not found: {source_path}, skipping.')
            continue
        
        # 如果目标文件存在，则生成新的文件名
        if os.path.exists(destination_path):
            destination_path = get_new_filename_if_exists(destination_path) # TODO: modify file_merge record file_name
        
        # 创建目标目录（如果不存在）
        os.makedirs(destination_dir, exist_ok=True)
        
        # copy文件
        shutil.copy(source_path, destination_path)
        
        # 更新数据库中的deal_flag
        cursor.execute('UPDATE file_merge SET deal_flag=1 WHERE id=?', (id,))
        db_conn.commit()

        print(f'copy: {source_path} to {destination_path}')

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="Scan directory and store file information into the database.")
    parser.add_argument('--db', required=True, help="Directory containing the SQLite database file (file_hash.db)")

    args = parser.parse_args()

    script_dir = args.db
    video_base_dir = args.db

    
    # 假设数据库文件位于脚本所在目录下的'E_RelaxArea_video'文件夹中
    db_path = os.path.join(script_dir, 'file_hash.db')

    # 创建/连接数据库
    conn = sqlite3.connect(db_path)

    # 移动文件并更新数据库
    move_files_and_update_db(conn, video_base_dir)

    # 关闭数据库连接
    conn.close()